package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    DishFlavorService dishFlavorService;

    @Override
    public void saveDish(DishDto dishDto) {
        //基础信息添加到dish中
        this.save(dishDto);

        //获得口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        Long id = dishDto.getId();
        if (flavors.size() > 0 && flavors != null) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
            }
            dishFlavorService.saveBatch(flavors);
        }
    }

    @Override
    public DishDto reGetById(long id) {
        Dish dish = this.getById(id);
        Long dishId = dish.getId();
        LambdaQueryWrapper<DishFlavor> qw=new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId,dishId);
        List<DishFlavor> list = dishFlavorService.list(qw);
        DishDto dishDto = new DishDto();
        dishDto.setFlavors(list);
        BeanUtils.copyProperties(dish,dishDto);
        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //基础先更新
        this.updateById(dishDto);

        Long id = dishDto.getId();
        LambdaQueryWrapper<DishFlavor> wq=new LambdaQueryWrapper<>();
        wq.eq(DishFlavor::getDishId,id);
        dishFlavorService.remove(wq);


        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
        }

       /* flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());*/


        dishFlavorService.saveBatch(flavors);
    }


}
